package cn.edu.csmzxy.rk233x.auth_system.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import cn.edu.csmzxy.rk233x.auth_system.dto.ResultDTO;
import cn.edu.csmzxy.rk233x.auth_system.dto.RoleDTO;
import cn.edu.csmzxy.rk233x.auth_system.entity.SysRole;
import cn.edu.csmzxy.rk233x.auth_system.service.SysRoleService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import jakarta.annotation.Resource;
import jakarta.validation.Valid;

/**
 * @author wumxing
 * @date 2025/10/15 9:54
 * @description  角色管理接口
 */

@Tag(name = "角色管理接口", description = "角色CRUD及权限分配")
@RestController
@RequestMapping("/api/sys/role")
@SecurityRequirement(name = "JWT")
public class SysRoleController {

    @Resource
    private SysRoleService sysRoleService;

    @Operation(summary = "分页查询角色", description = "需要role:list权限")
    @PreAuthorize("hasAuthority('role:list')")
    @GetMapping("/list")
    public ResultDTO<IPage<SysRole>> getRoleList(
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer pageNum,
            @Parameter(description = "每页条数") @RequestParam(defaultValue = "10") Integer pageSize,
            @Parameter(description = "角色名称模糊查询") @RequestParam(required = false) String roleName) {

        Page<SysRole> page = new Page<>(pageNum, pageSize);
        IPage<SysRole> rolePage = sysRoleService.selectRolePage(page, roleName);
        return ResultDTO.success(rolePage);
    }

    @Operation(summary = "新增角色", description = "需要role:add权限")
    @PreAuthorize("hasAuthority('role:add')")
    @PostMapping
    public ResultDTO<?> addRole(@Valid @RequestBody RoleDTO roleDTO) {
        sysRoleService.addRole(roleDTO);
        return ResultDTO.success("角色新增成功");
    }

    @Operation(summary = "编辑角色", description = "需要role:edit权限")
    @PreAuthorize("hasAuthority('role:edit')")
    @PutMapping("/{id}")
    public ResultDTO<?> updateRole(
            @Parameter(description = "角色ID") @PathVariable Long id,
            @Valid @RequestBody RoleDTO roleDTO) {
        sysRoleService.updateRole(id, roleDTO);
        return ResultDTO.success("角色修改成功");
    }

    @Operation(summary = "删除角色", description = "需要role:delete权限")
    @PreAuthorize("hasAuthority('role:delete')")
    @DeleteMapping("/{id}")
    public ResultDTO<?> deleteRole(@Parameter(description = "角色ID") @PathVariable Long id) {
        sysRoleService.deleteRole(id);
        return ResultDTO.success("角色删除成功");
    }

}
